package org.finalministry.gui.panels;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SpringLayout;

import org.finalministry.database.dao.DaoFactory;
import org.finalministry.gui.components.ColorSchema;
import org.finalministry.gui.components.CountrySelector;
import org.finalministry.gui.components.FLabel;
import org.finalministry.gui.utils.SpringUtilities;
import org.finalministry.objects.Congregation;

public class NewCongregationPanel extends JPanel implements ActionListener {

	private static final long serialVersionUID = 5316700380074480387L;

	private FTextField name;
	private NewAddressPanel address;
	private CountrySelector language;

	public NewCongregationPanel() {

		JPanel congregationBasicsPanel = new JPanel();
		congregationBasicsPanel.setBackground(ColorSchema.getBackgroundColor());
		congregationBasicsPanel.setLayout(new SpringLayout());

		FLabel labelLanguage = new FLabel("Language: ");
		congregationBasicsPanel.add(labelLanguage);
		language = new CountrySelector();
		congregationBasicsPanel.add(language);

		FLabel labelName = new FLabel("Congregation name: ");
		congregationBasicsPanel.add(labelName);
		name = new FTextField();
		congregationBasicsPanel.add(name);

		SpringUtilities.makeCompactGrid(congregationBasicsPanel, // parent
				2, 2, 3, 3, // initX, initY
				3, 3); // xPad, yPad

		this.add(congregationBasicsPanel);

		address = new NewAddressPanel();
		this.add(address);

		JButton saveCongregationButton = new JButton("Save");
		saveCongregationButton.addActionListener(this);
		this.add(saveCongregationButton);

		name.requestFocus();
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		String actionCommand = e.getActionCommand();

		if ("Save".equals(actionCommand)) {
			saveCongregation();
		}
	}

	private void saveCongregation() {
		try {
			Congregation congregation = new Congregation();
			congregation.setLanguage(language.getSelectedCountry());
			congregation.setName(name.getText());
			congregation.setAddress(address.getAddress());

			Long id = DaoFactory.getInstance().getCongregationDAO().create(congregation);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
